<?php

class filesUploader{
	
	var $db;
	var $errors=array(0,4);
	var $allowSize=61440;
	var $toReturn=array('ACTION' => 'error','SCRIPT' => array());
	
	/*
	 * Class constructor
	 */
	function filesUploader(){
		$db=new DB();
	}
	/*
	 * 
	 * @method() validateSize
	 * @description checks if the uploading file have the accepted size
	 * 
	 * @param files An array that contents the files to upload
	 * 
	 */
	function validateSize(& $files){
		foreach($files as $file){
			if($file['size']> $this->allowSize)
				return $this->toReturn['SCRIPT'][]= "alert('Los archivos no deven superar 60k')";
		}
		return true;
	}
	
	/*
	 * @method() uploadFiles
	 * @description function to storage files into database
	 * 
	 * 
	 * @param files array of files to upload
	 * 		  dataInfo array with storage information
	 * 		  	-0 identifier
	 * 			-1 date
	 * 			-2 update flag
	 * 			-3 file name
	 */
	function uploadFiles( & $files, & $dataInfo){
		foreach($files as $file){
			if(!empty($file['tmp_name'])){
				if(!in_array($file['error'],$this->errors)){
					$this->toReturn['SCRIPT'][]="alert('No se puede procesar el archivo {$dataInfo[3]} \n Error code:".$file['error']."')";
				}else{
					$i=(int)$dataInfo[0];
					$dte=date('d/m/Y',strtotime($dataInfo[1]));
					if(!empty($dataInfo[2])){
						$query="delete from images where id_img=$i";
						$this->db->query($query);
					}
					$fname=$files['tmp_name'];
					$fd=fopen($fname,'r');
					$Blob = fread($fd, filesize($fname));
					fclose($fd);
					unlink($fname);
					$query="Insert into images (id_img,date_img,image) values({$i},'{$dte}',{$Blob})";
					$this->db->query($query);
					//Anexar if exito o no 	
					$this->toReturn['SCRIPT'][]="alert('Archivo {$dataInfo[3]} recibido con exito')";
					//opcion else
					$this->toReturn['SCRIPT'][]="alert('Fallo al en enviar el archivo {$dataInfo[3]}')";	
				}
			}
		}
		return $this->toReturn;
	}
	
	/*
	 * 
	 * @method() getImage
	 * @description Function that returns and image storaged in the database
	 * 
	 * @param id Identifier of the image to return
	 *  
	 */
	function getImage($id){
		$query="Select image from images where id_img={$id}";
		$this->db->query($query);
		$im=$this->db->getRow();
		$img=$im['image'];
		
		print $img;
	}
}
?>